package com.yuandian.customer.perception.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.customer_perception.po.BasePortraitParams;
import com.yuandian.api.customer_perception.vo.OperatorActiveTrendVo;
import com.yuandian.api.customer_perception.vo.OperatorProcessCountTop5VO;
import com.yuandian.api.customer_perception.vo.TimeConsumingTop5;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.mapper.UnitPortraitMapper;
import com.yuandian.customer.perception.service.IUnitPortraitService;
import com.yuandian.enums.TableNameEnum;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author liXin
 * @description 单位画像
 * @date 2022/4/24
 */
@Service
public class UnitPortraitServiceImpl implements IUnitPortraitService {

    @Autowired
	UnitPortraitMapper unitPortraitServiceMapper;


    /**
     * 单位操作员事项操作平均耗时排行(TOP5)
     */
    @Override
    public R<Object> queryOperatorBusinessProcessAvgTimeTop5(BasePortraitParams params) {
        // 默认按照用户办理事项的平局办理时长排序,若平均时间时长相同,则按照用户姓氏首字母升序排序
        HashMap<String, List<TimeConsumingTop5>> map = new HashMap<>();
        params.setOrderByColumn(Optional.ofNullable(params.getOrderByColumn()).orElse("avgDealTime"));
        List<TimeConsumingTop5> longTimeMatter = unitPortraitServiceMapper.queryMatterByLongestProcessTimeTop5(params);
        List<TimeConsumingTop5> shortTimeMatter = unitPortraitServiceMapper.queryMatterByShortestProcessTimeTop5(params);
        map.put("longProcessTimeMatter", longTimeMatter);
        map.put("shortProcessTimeMatter", shortTimeMatter);
        return R.ok(map);
    }


    /**
     * 单位操作员活跃时段(趋势图)
     */
    @Override
    public R<Object> queryOperatorActiveDuration(BasePortraitParams params) {
        // 判断开始时间和结束时间是否间隔是否大于一天，
        // 如果大于一天，求出开始时间到结束时间的表名
        boolean isCrossDay= YDateUtil.checkTime(params.getStartTime(),params.getEndTime());
        if (isCrossDay){
            //计算开始时间到结束时间之间的表名，
            List<String> tableNames = Collections.singletonList(TableNameEnum.BUSI_STEP_AFFAIR_M.getName());

			List<OperatorActiveTrendVo> list = unitPortraitServiceMapper.queryOperatorActiveDDuration(tableNames,params);
			list.forEach(operatorActiveTrendVo -> {
				String endTime=  YDateUtil.getAfterMinuteStr(operatorActiveTrendVo.getCycleTime(),1440);
				operatorActiveTrendVo.setEndTime(endTime);
			});

            List<OperatorActiveTrendVo> resultList=mergeData(params.getStartTime(),params.getEndTime(),list);

            return R.ok(resultList);

        } else {

            // 计算开始时间那一天24小时的活跃数
             String tableName = TableNameEnum.BUSI_STEP_AFFAIR_M.getName();
            List<OperatorActiveTrendVo> list = unitPortraitServiceMapper.queryOperatorActiveHDuration(tableName,params);
            list.forEach(operatorActiveTrendVo -> {
				String endTime= YDateUtil.getAfterMinuteStr(operatorActiveTrendVo.getCycleTime(),1440);
                operatorActiveTrendVo.setEndTime(endTime);
            });

            HashMap<String,Object> result=new HashMap<>();
            List<OperatorActiveTrendVo> resultList=mergeData(params.getStartTime(),params.getEndTime(),list);
            result.put("list",resultList);
            result.put("yesterday",YDateUtil.mm_dd(params.getStartTime()));

            String beforeDayStartTime= YDateUtil.getBeforeDayTime(params.getStartTime(),1);
            String beforeDayEndTime= YDateUtil.getBeforeDayTime(params.getEndTime(),1);
            String tableName1 = TableNameEnum.BUSI_STEP_AFFAIR_M.getName();
            params.setStartTime(beforeDayStartTime);
            params.setEndTime(beforeDayEndTime);
            List<OperatorActiveTrendVo> list1 = unitPortraitServiceMapper.queryOperatorActiveHDuration(tableName1,params);
			list1.forEach(operatorActiveTrendVo -> {
				String endTime= YDateUtil.getAfterMinuteStr(operatorActiveTrendVo.getCycleTime(),60);
				operatorActiveTrendVo.setEndTime(endTime);
			});

            List<OperatorActiveTrendVo> resultList1=mergeData(params.getStartTime(),params.getEndTime(),list1);

            result.put("beforeList",resultList1);
            result.put("beforeday", YDateUtil.mm_dd(beforeDayStartTime));

			return R.ok(result);
        }
    }

    /**
     * 操作员活跃时段list
     */
    @Override
    public R<Object> queryOperatorActiveList(BasePortraitParams params) {
        String tableName=TableNameEnum.BUSI_STEP_AFFAIR_M.getName();
        // 设置分页参数
        Page<OperatorActiveTrendVo> page = new Page<>(params.getPageNum(), params.getPageSize());
        List<OperatorActiveTrendVo> list = unitPortraitServiceMapper.queryOperatorActiveList(tableName, params, page);
	 	return R.ok(new PageDataInfo(page, list));
    }


    /**
     * 单位操作员办理排行(TOP5)
     */
    @Override
    public R<Object> queryOperatorBusinessProcessCountTop5(BasePortraitParams params) {

        // 事项变化表
        String itemChangeTable = TableNameEnum.BUSI_ITEM_CHANGE.getName();
		if (StringUtils.isBlank(params.getIsAsc())){ params.setIsAsc("asc"); }

		List<OperatorProcessCountTop5VO> busiStepAffairVos = unitPortraitServiceMapper.queryOperatorBusinessProcessCountTop5(params, itemChangeTable);

        return R.ok(busiStepAffairVos);
    }


    /**
     * 活跃操作员人数
     */
    @Override
    public R<Object> queryActiveOperationcount(BasePortraitParams params) {
        HashMap<String, Integer> map = new HashMap<>();
        Integer activeOperatorCount = unitPortraitServiceMapper.queryActiveOperationcount(params);
        map.put("activeOperatorCount", activeOperatorCount);
        return R.ok(map);
    }


	/**
	 * 合并数据
	 */
    private synchronized List<OperatorActiveTrendVo> mergeData(String startTime,String endTime,List<OperatorActiveTrendVo> list){
        // 根据开始时间和结束时间生成时间轴，一个小时一个实例
        List<OperatorActiveTrendVo> list1 = new ArrayList<>();
        OperatorActiveTrendVo vo = new OperatorActiveTrendVo();
        vo.setCycleTime(startTime);
        vo.setEndTime(YDateUtil.getAfterMinuteStr(startTime,60));
        vo.setPeopleCount(0);
        list1.add(vo);

        while (YDateUtil.compare(YDateUtil.getAfterMinuteStr(list1.get(list1.size()-1).getCycleTime(),60),endTime) < 0){
            OperatorActiveTrendVo newVo=new OperatorActiveTrendVo();
            newVo.setCycleTime(list1.get(list1.size()-1).getEndTime());
            newVo.setEndTime(YDateUtil.getAfterMinuteStr(newVo.getCycleTime(),60));
            newVo.setPeopleCount(0);
            list1.add(newVo);
        }

        // 用map存储，key为cycle_time
        LinkedHashMap<String,OperatorActiveTrendVo> newHashMap=new LinkedHashMap<>();
        list1.forEach(operatorActiveTrendVo->{
            newHashMap.put(operatorActiveTrendVo.getCycleTime(),operatorActiveTrendVo);
        });

        // 然后遍历list，将数据存入map
        list.forEach(operatorActiveTrendVo -> {
            OperatorActiveTrendVo voChild=newHashMap.get(operatorActiveTrendVo.getCycleTime());
            voChild.setPeopleCount(operatorActiveTrendVo.getPeopleCount());
        });

        // 遍历map，将数据转存list，输出
        List<OperatorActiveTrendVo> result=new ArrayList<>();
        newHashMap.forEach((s, operatorActiveTrendVo) -> {
            result.add(operatorActiveTrendVo);
        });

        return result;
    }
}
